package com.han.fu.api.common.utils;

import com.han.fu.api.common.exception.BusinessException;
import com.han.fu.common.constants.RedisKeyConstants;
import com.han.fu.common.constants.StringConstants;
import com.han.fu.api.common.model.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 当前用户
 *
 * @author: star
 * @date: 2021-01-18
 */
@Component
public class CurrentUserUtil {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    HttpServletRequest request;

    private static final String EXPORT = "/export";

    /**
     * 获取用户
     *
     * @return
     * @ignore
     */
    public UserDetail getUser() {
        String token = this.getToken();
        if (StringUtils.hasText(token)) {
            ValueOperations<String, UserDetail> valueOperations = redisTemplate.opsForValue();
            UserDetail userDetail = valueOperations.get(RedisKeyConstants.AUTH_TOKEN.concat(token));
            if (null == userDetail || null == userDetail.getId()) {
                throw new BusinessException("认证失败：token不存在");
            }
            return userDetail;
        } else {
            throw new BusinessException("认证失败：token无效");
        }
    }

    /**
     * 获取token
     *
     * @return
     * @ignore
     */
    public String getToken() {
        String token = this.request.getHeader(StringConstants.TOKEN_HEADER);
        if (StringUtils.hasText(token)) {
            return token;
        } else {
            String uri = this.request.getRequestURI();
            if (StringUtils.hasText(uri) && uri.startsWith(EXPORT)) {
                return this.request.getParameter(StringConstants.TOKEN_HEADER);
            }
        }
        throw new BusinessException("认证失败：token无效");
    }

}
